<template>
  <div>
    <el-card>
      <div slot="header">
        <!-- 面包屑 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>{{
            $route.query.id ? '修改文章' : '发布文章'
          }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-form
        ref="publishFormRef"
        :model="publishForm"
        label-width="60px"
        :rules="publishFormRules"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="publishForm.title"
            placeholder="至少五个字符"
          ></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-tiptap
            v-model="publishForm.content"
            :extensions="extensions"
            lang="zh"
            height="360"
            placeholder="请输入文章内容"
          ></el-tiptap>
          <!-- <el-input v-model="publishForm.content" type="textarea"></el-input> -->
        </el-form-item>
        <el-form-item label="封面">
          <el-radio-group v-model="publishForm.cover.type">
            <el-radio :label="1">单图</el-radio>
            <el-radio :label="3">三图</el-radio>
            <el-radio :label="0">无图</el-radio>
            <el-radio :label="-1">自动</el-radio>
          </el-radio-group>
          <template v-if="publishForm.cover.type > 0">
            <div class="pailie">
              <upload-cover
                v-for="(item, index) in publishForm.cover.type"
                :key="item"
                v-model="publishForm.cover.images[index]"
              ></upload-cover>
            </div>
          </template>
        </el-form-item>
        <el-form-item label="频道" prop="channel_id">
          <el-select v-model="publishForm.channel_id" placeholder="请选择频道">
            <el-option
              v-for="item in channels"
              :label="item.name"
              :value="item.id"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onPublish(false)">发布</el-button>
          <el-button type="" @click="onPublish(true)">存入草稿</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import UploadCover from './components/upload-cover'
import {
  getArticleChannels,
  addArticle,
  updateArticle,
  getArticle
} from '@/api/article'
import {
  ElementTiptap,
  Doc,
  Text,
  Paragraph,
  Heading,
  Bold,
  Underline,
  Italic,
  Image,
  Strike,
  ListItem,
  BulletList,
  OrderedList,
  TodoItem,
  TodoList,
  HorizontalRule,
  Fullscreen,
  Preview,
  CodeBlock,
  TextColor
} from 'element-tiptap'
import 'element-tiptap/lib/index.css'
import { uploadImage } from '@/api/image'
export default {
  name: 'PublishIndex',
  components: {
    'el-tiptap': ElementTiptap,
    'upload-cover': UploadCover
  },
  data() {
    return {
      publishForm: {
        title: '',
        content: '',
        cover: {
          type: 1,
          images: []
        },
        channel_id: null
      },
      channels: [],
      publishFormRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          {
            require: true,
            min: 5,
            max: 30,
            message: '长度在 5 到 30 个字符',
            trigger: 'blur'
          }
        ],
        content: [
          // { required: true, message: '请输入文章内容', trigger: 'blur' },
          {
            validator(rule, value, callback) {
              if (value === '<p></p>') {
                callback(new Error('请输入文章内容'))
              } else {
                callback()
              }
            }
          },
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ],
        channel_id: [{ required: true, message: '请选择频道' }]
      },
      extensions: [
        new Doc(),
        new Text(),
        new Paragraph(),
        new Heading({ level: 3 }),
        new Bold({ bubble: true }), // 在气泡菜单中渲染菜单按钮
        new Image({
          // 默认会把图片生成 base64 字符串和内容存储在一起，如果需要自定义图片上传
          uploadRequest(file) {
            // 此插件的方法
            // 如果接口要求 Content-Type 是 multipart/form-data，则请求体必须使用 FormData
            const fd = new FormData()
            fd.append('image', file)
            // 第1个 return 是返回 Promise 对象
            // 为什么？因为 axios 本身就是返回 Promise 对象
            return uploadImage(fd).then((res) => {
              // 这个 return 是返回最后的结果
              return res.data.data.url
            })
          } // 图片的上传方法，返回一个 Promise<url>
        }),
        new Underline(), // 下划线
        new Italic(), // 斜体
        new Strike(), // 删除线
        new HorizontalRule(), // 华丽的分割线
        new ListItem(),
        new BulletList(), // 无序列表
        new OrderedList(), // 有序列表
        new TodoItem(),
        new TodoList(),
        new Fullscreen(),
        new Preview(),
        new CodeBlock(),
        new TextColor()
      ]
    }
  },
  created() {
    this.loadChannels()
    if (this.$route.query.id) {
      this.loadArticle()
    }
  },
  methods: {
    loadChannels() {
      getArticleChannels().then((res) => {
        this.channels = res.data.data.channels
      })
    },
    onPublish(draft = false) {
      this.$refs.publishFormRef.validate((valid) => {
        if (!valid) {
          return false
        } else {
          const articleId = this.$route.query.id
          if (articleId) {
            updateArticle(articleId, this.publishForm, draft).then((res) => {
              this.$message.success('修改成功')
              this.$router.push('/article')
            })
          } else {
            addArticle(this.publishForm, draft)
              .then((res) => {
                this.$message.success(
                  `${draft ? '存入草稿成功！' : '发布成功！'}`
                )
                this.$router.push('/article')
              })
              .catch(() => {
                this.$message.error('发布失败！')
              })
          }
        }
      })
    },
    loadArticle() {
      getArticle(this.$route.query.id).then((res) => {
        this.publishForm = res.data.data
      })
    },
    onUpdateCover(index, url) {
      this.publishForm.cover.images[index] = url
    }
  }
}
</script>
<style lang="less" scoped>
.pailie {
  display:flex;
}
</style>
